<template>
  <div class="customer-container">
    <!-- 查询 -->
    <div class="search-container">
      <el-select
          v-model="selectedCategory"
          placeholder="客户分类"
          @change="fetchCustomers"
          style="width: 150px"
          class="search-select"
      >
        <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
        ></el-option>
      </el-select>
      <el-input
          placeholder="请输入客户姓名"
          style="width: 200px"
          v-model="queryName"
          class="search-input"
          clearable
          @keyup.enter="queryByName"
      ></el-input>
      <el-button
          @click="queryByName"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
    </div>

    <!-- 客户信息表格 -->
    <el-table
        :data="customerList"
        class="customer-table"
        header-cell-class-name="table-header"
    >
      <el-table-column
          label="序号"
          type="index"
          width="60px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerName"
          label="客户姓名"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="customerSex"
          label="性别"
          width="80px"
          align="center"
      >
        <template #default="scope">
          {{ scope.row.customerSex === 0 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column
          prop="customerAge"
          label="年龄"
          width="80px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="buildingNo"
          label="所属楼房"
          width="100px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="checkinDate"
          label="入住日期"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="expirationDate"
          label="合同到期时间"
          width="120px"
          align="center"
          :formatter="formatDate"
      ></el-table-column>
      <el-table-column
          prop="contactTel"
          label="联系电话"
          width="120px"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="familyMember"
          label="家属"
          width="80px"
          align="center"
      ></el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #default="scope">
          <template v-if="selectedCategory === 'all' || selectedCategory === 'active'">
            <el-button
                v-if="scope.row.status === 0 || scope.row.status === 2"
                type="danger"
                size="small"
                @click="showCheckoutDialog(scope.row.id)"
                class="checkout-button"
            >
              退住
            </el-button>
          </template>
          <template v-if="selectedCategory === 'all' || selectedCategory === 'inactive'">
            <el-button
                v-if="scope.row.status === 1"
                type="warning"
                size="small"
                @click="showDetailDialog(scope.row.id)"
                class="backdown-button"
            >
              退住信息
            </el-button>
            <el-button
                v-if="scope.row.status === 1"
                type="warning"
                size="small"
                @click="showEditDialog(scope.row.id)"
                class="edit-backdown-button"
            >
              修改
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 通用退住信息对话框 -->
    <!-- 退住信息对话框 -->
    <el-dialog
        v-model="backdownDialog"
        :title="dialogTitle"
        class="backdown-dialog"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form :model="curBackdown" class="backdown-form" :rules="rules" ref="backdownForm">
        <el-form-item label="客户ID" prop="customerId" class="form-item">
          <el-input
              placeholder="输入客户ID"
              v-model="curBackdown.customerId"
              class="form-input"
              clearable
              :disabled="dialogOptType === 3"
          ></el-input>
        </el-form-item>
        <el-form-item label="客户姓名" class="form-item">
          <el-input
              v-model="curBackdown.customerName"
              class="form-input"
              :disabled="dialogOptType === 3"
          ></el-input>
        </el-form-item>
        <el-form-item label="退住时间" prop="retreattime" class="form-item">
          <el-date-picker
              v-model="curBackdown.retreattime"
              class="form-date-picker"
              placeholder="选择退住时间"
              :disabled="dialogOptType === 3"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="退住类型" prop="retreattype" class="form-item">
          <el-select
              v-model="curBackdown.retreattype"
              class="form-select"
              :disabled="dialogOptType === 3"
          >
            <el-option
                v-for="item in retreatTypeOptions"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="退住原因" prop="retreatreason" class="form-item">
          <el-input
              v-model="curBackdown.retreatreason"
              class="form-input"
              placeholder="请输入退住原因"
              :disabled="dialogOptType === 3"
          ></el-input>
        </el-form-item>
        <el-form-item label="审批状态" prop="auditstatus" class="form-item">
          <el-select
              v-model="curBackdown.auditstatus"
              class="form-select"
              :disabled="dialogOptType === 3"
          >
            <el-option
                v-for="item in auditStatusOptions"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审批人" prop="auditperson" class="form-item">
          <el-input
              v-model="curBackdown.auditperson"
              class="form-input"
              placeholder="请输入审批人"
              :disabled="dialogOptType === 3"
          ></el-input>
        </el-form-item>
        <el-form-item label="审批时间" prop="audittime" class="form-item">
          <el-date-picker
              v-model="curBackdown.audittime"
              class="form-date-picker"
              placeholder="选择审批时间"
              :disabled="dialogOptType === 3"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="closeBackdownDialog" class="dialog-button">取消</el-button>
        <el-button
            type="primary"
            @click="optOne"
            class="dialog-button"
            :loading="submitting"
            v-if="dialogOptType !== 3"
        >
          {{ buttonOpt }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http';
import qs from "qs";
import { ElMessage, ElMessageBox } from 'element-plus';

// 客户数据集合
let customerList = ref([]);

// 分类
let selectedCategory = ref("all");
let categories = ref([
  { label: "历史客户", value: "all" },
  { label: "在住客户", value: "active" },
  { label: "已退住客户", value: "inactive" },
]);

// 查询关键字
let queryName = ref("");

// 对话框显示控制
let backdownDialog = ref(false);

// 当前操作的客户或退住信息
let curBackdown = ref({
  customerId: null,
  customerName: '',
  retreattime: null,
  retreattype: null,
  retreatreason: '',
  auditstatus: null,
  auditperson: '',
  audittime: null
});

// 对话框标题和按钮文本
let dialogTitle = ref("");
let buttonOpt = ref("");
let dialogOptType = ref(1); // 1:新增 2:编辑 3:查看

// 分页相关
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 提交状态
let submitting = ref(false);

// 表单验证
const backdownForm = ref(null);
const rules = reactive({
  customerId: [
    { required: true, message: '客户ID不能为空', trigger: 'blur' }
  ],
  retreattime: [
    { required: true, message: '退住时间不能为空', trigger: 'blur' }
  ],
  retreattype: [
    { required: true, message: '退住类型不能为空', trigger: 'blur' }
  ],
  retreatreason: [
    { required: true, message: '退住原因不能为空', trigger: 'blur' }
  ],
  auditstatus: [
    { required: true, message: '审批状态不能为空', trigger: 'blur' }
  ],
  auditperson: [
    { required: true, message: '审批人不能为空', trigger: 'blur' }
  ],
  audittime: [
    { required: true, message: '审批时间不能为空', trigger: 'blur' }
  ]
});

// 退住类型数组
let retreatTypeOptions = ref([
  {
    label: '正常退住',
    value: 0
  },
  {
    label: '死亡退住',
    value: 1
   }
  // {
  //   label: '保留床位',
  //   value: 2
  // }
]);

// 审批状态数组
let auditStatusOptions = ref([
  // {
  //   label: '已提交',
  //   value: 0
  // },
  {
    label: '同意',
    value: 1
  },
  // {
  //   label: '拒绝',
  //   value: 2
  // }
]);

// 格式化日期
function formatDate(row, column) {
  let data = row[column.property];
  if (data == null) {
    return null;
  }
  let dt = new Date(data);
  return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate();
}

// 根据分类获取客户信息
function fetchCustomers() {
  let param = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    category: selectedCategory.value
  };
  http.post('/lyy/get_customers_by_category', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      customerList.value = result.data.list;
    } else {
      ElMessage.error(result.error);
    }
  });
}

// 根据姓名模糊查询客户信息
function queryByName() {
  let param = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize,
    customerName: queryName.value.trim()
  };
  http.post('/lyy/get_customers_by', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      pageContains.value = result.data;
      customerList.value = result.data.list;
    } else {
      ElMessage.error(result.error);
    }
  });
}

// 显示退住对话框
function showCheckoutDialog(customerId) {
  getCustomerInfo(customerId);
  dialogTitle.value = "客户退住登记";
  buttonOpt.value = "确认退住";
  dialogOptType.value = 1; // 新增
  backdownDialog.value = true;
}

// 显示详细信息对话框
function showDetailDialog(customerId) {
  console.log('尝试查看退住信息，customerId:', customerId); // 调试用
  http.post('/lyy/get_backdown_by_id', qs.stringify({ customerId }))
      .then(res => {
        if (res.data.result === 'success') {
          curBackdown.value = res.data.data;
          dialogTitle.value = "查看退住信息";
          buttonOpt.value = "关闭";
          dialogOptType.value = 3; // 查看
          backdownDialog.value = true;
        } else {
          ElMessage.error(res.data.error || '获取退住信息失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取退住信息出错:', error);
      });
}

// 显示编辑对话框
function showEditDialog(customerId) {
  console.log('尝试编辑退住信息，customerId:', customerId); // 调试用
  http.post('/lyy/get_backdown_by_id', qs.stringify({ customerId }))
      .then(res => {
        if (res.data.result === 'success') {
          curBackdown.value = res.data.data;
          dialogTitle.value = "修改退住信息";
          buttonOpt.value = "保存修改";
          dialogOptType.value = 2; // 编辑
          backdownDialog.value = true;
        } else {
          ElMessage.error(res.data.error || '获取退住信息失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('获取退住信息出错:', error);
      });
}

// 获取客户信息
function getCustomerInfo(customerId) {
  http.post('/lyy/getcustomerby_id', qs.stringify({ customerid: customerId })).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      curBackdown.value.customerId = result.data.id;
      curBackdown.value.customerName = result.data.customerName;
    } else {
      ElMessage.error(result.error);
    }
  });
}

// 确认操作
function optOne() {
  if (dialogOptType.value === 1) {
    confirmCheckout();
  } else if (dialogOptType.value === 2) {
    saveEditBackdown();
  }
}

// 确认退住
function confirmCheckout() {
  submitting.value = true;
  let param = {
    customerId: curBackdown.value.customerId,
    retreattype: curBackdown.value.retreattype,
    retreatreason: curBackdown.value.retreatreason,
    retreattime: curBackdown.value.retreattime,
    auditstatus: curBackdown.value.auditstatus,
    auditperson: curBackdown.value.auditperson,
    audittime: curBackdown.value.audittime
  };
  http.post('/lyy/add_one_backdown', param).then((res) => {
    let result = res.data;
    if (result.result === 'success') {
      ElMessage.success('退住成功');
      closeBackdownDialog();
      fetchCustomers();
    } else {
      ElMessage.error(result.error);
    }
  }).finally(() => {
    submitting.value = false;
  });
}

// 保存修改的退住信息
function saveEditBackdown() {
  submitting.value = true;
  let param = curBackdown.value;
  http.post('/lyy/modify_backdown_by_id', param)
      .then(res => {
        if (res.data.result === 'success') {
          ElMessage.success('修改成功');
          closeBackdownDialog();
          fetchCustomers();
        } else {
          ElMessage.error(res.data.error || '修改失败');
        }
      })
      .catch(error => {
        ElMessage.error('网络请求出错，请稍后重试');
        console.error('修改退住信息出错:', error);
      })
      .finally(() => {
        submitting.value = false;
      });
}

// 关闭对话框
function closeBackdownDialog() {
  backdownDialog.value = false;
  curBackdown.value = {};
  if (backdownForm.value) {
    backdownForm.value.resetFields();
  }
}

// 分页处理
const handlePageChange = (newPage) => {
  pageContains.value.pageNum = newPage;
  fetchCustomers();
};

const handleSizeChange = (newSize) => {
  pageContains.value.pageSize = newSize;
  fetchCustomers();
};

// 页面初始化
onMounted(() => {
  fetchCustomers();
});
</script>

<style scoped>
.customer-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.customer-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.backdown-dialog {
  width: 500px;
}

.backdown-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input, .form-date-picker, .form-select {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}
</style>